package edu.ynu.se.xiecheng.achitectureclass.common.utils;

import edu.ynu.se.xiecheng.achitectureclass.common.dto.CameraDeviceTokenResponseDTO;
import okhttp3.*;
import com.google.gson.Gson;

import java.io.IOException;

public class CameraDeviceTokenUtil {

    private static final String TOKEN_URL = "http://42.193.14.241:7000/ysapi/subAccount/getToken";
    private static final MediaType MEDIA_TYPE = MediaType.parse("application/json");

    public static CameraDeviceTokenResponseDTO getToken(String accountId) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Gson gson = new Gson();

        while (true) {
            try {
                String json = String.format("{\"accountId\": \"%s\"}", accountId);

                RequestBody body = RequestBody.create(json, MEDIA_TYPE);
                Request request = new Request.Builder()
                        .url(TOKEN_URL)
                        .post(body)
                        .header("Content-Type", "application/json")
                        .build();

                try (Response response = client.newCall(request).execute()) {
                    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                    String responseBody = response.body().string();
                    return gson.fromJson(responseBody, CameraDeviceTokenResponseDTO.class);
                }
            } catch (IOException e) {
                try {
                    Thread.sleep(500); // 等待0.5秒
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    throw new IOException("Thread interrupted", ie);
                }
            }
        }
    }


    public static void main(String[] args) {
        try {
            String accountId = "1ca7f0ab24ba41b291346347ec30140e";
            CameraDeviceTokenResponseDTO cameraDeviceTokenResponseDTO = getToken(accountId);
            System.out.println("Access Token: " + cameraDeviceTokenResponseDTO.getData().getAccessToken());
            System.out.println("Expire Time: " + cameraDeviceTokenResponseDTO.getData().getExpireTime());
            System.out.println("Code: " + cameraDeviceTokenResponseDTO.getCode());
            System.out.println("Message: " + cameraDeviceTokenResponseDTO.getMsg());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
